import {Avatar, Button, Col, Divider, message, Popconfirm, Row} from 'antd';
import {ModalForm} from "@ant-design/pro-form";
import {ProList} from "@ant-design/pro-list";
import {useEffect, useRef, useState} from "react";
import {
  addFamily,
  deleteFamily,
  queryAllIcon,
  queryFamily,
  updateFamily
} from "@/pages/User/Account/settings/components/service";
import {DeleteOutlined} from "@ant-design/icons";
import type {ProFormInstance} from "@ant-design/pro-form";
import { ProFormText} from "@ant-design/pro-form";
import {Selector, Toast} from "antd-mobile";
import IconUpdateForm from "@/pages/User/Account/settings/components/components/IconUpdateForm";

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: any) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteFamily({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        Toast.show({
          content: res.message,
          icon: "success"
        })
        return true;
      } else {
        Toast.show({
          content: res.message,
          icon: "fail"
        })
        return false;
      }
    } else {
      Toast.show({
        content: '请求超时，请稍后重试',
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '删除失败，请重试',
      icon: "fail"
    })
    return false;
  }
};

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加...');

  try {
    const res = await addFamily({ ...fields });
    if (res && res.status === 'done') {
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    } else {
      hide();
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '添加失败，请重试！',
      icon: "fail"
    })
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleUpdate = async (fields: any, currentRow?: any) => {
  const hide = message.loading('正在处理');

  try {
    const res = await updateFamily({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '更新失败，请重试！',
      icon: "fail"
    })
    return false;
  }
};

export default () => {
  const formRef = useRef<ProFormInstance>();
  const [dataSource, setDatasource] = useState<any[]>([])
  const [update, setUpdate] = useState<boolean>(true)
  const [currentRow, setCurrentRow] = useState<any>(undefined)
  const [iconFormVisible, handleIconFormVisible] = useState<boolean>(false)
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  // 从后台获取数据
  useEffect(() => {
    queryFamily().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...dataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: any)=>{
          data.push({
            name: item.name,
            id: item.id,
            images: "/static/icons/" + item.icon,
            icon: item.icon
          })
        })
        setDatasource(data)
      }
    })
  }, [update]);

  // 从后台获取所有Icon
  const [iconSource, setIconSource] = useState<any[]>([])
  useEffect(() => {
    queryAllIcon().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...iconSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: string)=>{
          data.push({
            label: <Avatar src={"/static/icons/"+item}/>,
            value: item,
          })
        })
        setIconSource(data)
      }
    })
  }, []);

  return (
    <>
      <Button style={{width: `100%`}} key="add" type="primary" onClick={()=>{handleModalVisible(true)}}>
        新增支出成员
      </Button>
      <Divider/>
    <ProList<any>
      rowKey="name"
      split={true}
      size={"small"}
      dataSource={dataSource}
      metas={{
        title: {
          dataIndex: 'name',
        },
        avatar: {
          dataIndex: 'images',
          editable: false,
        },
        actions: {
          render: (text: any, row: { name: string, icon: string, images: string }) => [
            <a
              key="edit"
              onClick={()=>{
                setCurrentRow(row)
                handleIconFormVisible(true)
              }}
            >
              修改
            </a>,
            <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
              const success = await handleSingleRemove(row);
              if (success) {
                if (update){
                  setUpdate(false)
                }else {
                  setUpdate(true)
                }
              }
            }}>
              <a style={{color: "red"}} ><DeleteOutlined /> 删除</a>
            </Popconfirm>
          ],
        },
      }}
    />
      <ModalForm
        title="新增消费成员"
        width="830px" // 注销可由其自动管理宽度
        visible={createModalVisible}
        formRef={formRef}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (update){
              setUpdate(false)
            }else {
              setUpdate(true)
            }
          }
        }}
      >
        <ProFormText
          name={"name"}
          label={"成员名称"}
          rules={[{required: true, message: "必填！"}]}
        />
        <ProFormText
          name={"icon"}
          hidden
        />
        <Row style={{marginBottom: 10}}>
          <span style={{marginBottom: 8}}>成员图标</span>
          <Col span={24} style={{height: `calc(100vh - 420px)`, overflowY:"auto"}}>
            <Selector
              key={Date.now()}
              columns={5}
              options={iconSource}
              // defaultValue={}
              multiple={false}
              showCheckMark={true}
              style={{
                // '--checked-color': "#fa541c",
                // '--checked-text-color': "white",
                '--gap': "3px",
              }}
              onChange={(value)=>{
                formRef.current?.setFieldsValue({
                  icon: value[0]
                })
              }}
            />
          </Col>
        </Row>
      </ModalForm>
      <IconUpdateForm
        onCancel={()=>{
          setCurrentRow(undefined)
          handleIconFormVisible(false)
        }}
        onSubmit={async (value)=>{
          const success = await handleUpdate(value, currentRow);
          if (success){
            handleIconFormVisible(false)
            setCurrentRow(undefined)
            // 更新数据
            if (update){
              setUpdate(false)
            }else {
              setUpdate(true)
            }
          }
        }}
        modalVisible={iconFormVisible}
        values={currentRow || {}}
      />
    </>
  );
};
